package com.demo.service.impl;

import com.demo.bean.DemoException;
import com.demo.service.ExceptionService;
import com.demo.util.ExceptionUtil;
import com.mapper.ExceptionMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;

@Service
public class ExceptionServiceImpl implements ExceptionService {
    Logger LOGGER = LoggerFactory.getLogger(ExceptionServiceImpl.class);
    @Autowired
    private ExceptionMapper errorMapper;

    @Override
    public void saveExceptionSimple(String type, Exception ex) {
        saveExceptionDetail(null, type, ex);
    }

    @Override
    public void saveExceptionMessage(Long budinessId, String type, String msg) {
        LOGGER.error(type+":"+msg);
        try {
            DemoException exception = new DemoException();
            exception.setBusinessType(type);
            exception.setCreateTime(new Timestamp(System.currentTimeMillis()));
            exception.setErrorMessage(msg);
            exception.setBusinessId(budinessId);
            errorMapper.insert(exception);
        } catch (Exception e) {
            //日志输出不影响原有业务
            String s = ExceptionUtil.getThrowableMessage(e);
            LOGGER.error(s);
        }
    }

    @Override
    public void saveExceptionDetail(Long budinessId, String type, Exception ex) {
        //拿到全部异常
        String msg = ExceptionUtil.getThrowableMessage(ex);
        saveExceptionMessage(budinessId, type, msg);
    }
}
